package com.abigdreamer.wordpress.newspider;

import java.util.ArrayList;
import java.util.List;

/**
 * 
 * @author Darkness
 * @date 2013-6-2 下午04:39:59
 * @website http://www.abigdreamer.com
 * @version V1.0
 */
public class ThreadTaskManager<T> {
	public  long startTime = System.currentTimeMillis();
	private  ArrayList<T> tasks = new ArrayList<T>();// 存储未处理URL
	private int finishCount = 0;
	private int totalCount = 0;

	private List<ThreadTaskProcesser> spiders = new ArrayList<ThreadTaskProcesser>();

	public void addProcesser(ThreadTaskProcesser spider) {
		spiders.add(spider);
	}

	protected void startThread() {
		for (ThreadTaskProcesser spider : spiders) {
			new Thread(spider).start();
		}
	}

	public synchronized T getTask() {
		if (tasks.size() > 0) {

			T tmp = null;
			tmp = tasks.get(0);
			tasks.remove(0);

			finishCount++;
			System.out.println("完成度：" + ((finishCount * 100.0) / totalCount) + "%" + "，耗时：" + (System.currentTimeMillis() - startTime) / 1000 + "s");

			return tmp;
		} else
			return null;
	}

	public void addTask(T task) {
		totalCount++;
		tasks.add(task);
	}
	
	public void addTasks(List<T> _tasks) {
		totalCount += _tasks.size();
		tasks.addAll(_tasks);
	}

	private boolean isFinished = false;
	
	public boolean isFinished() {
		for (ThreadTaskProcesser spider : spiders) {
			if (spider.isRuning) {
				return false;
			}
		}
		
		if(isFinished) 
			return true;
		
		synchronized (this) {
			if(isFinished) 
				return true;
			
			isFinished = true;
			
			System.out.println("共耗时：" + (System.currentTimeMillis() - startTime) / 1000 + "s");
			afterFinished();
		}

		return true;
	}

	protected void afterFinished() {
	}
}
